// pages/housetype/mine.js
const app = getApp()
const utils = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    barHeight: app.globalData.navHeight,
    focusFlag:false,
    canSearch:true,
    typeTopTitle:"我的户型",
    headerBgSrc:"",
    locationWidth:0,
    buildName:"",
    latitude:"",//纬度
    longitude:"",//经度
    userLocation:"",
    subLocationInfo:"",
    searchListFlag:false,
    searchBoxHeight:0,
    searchList:[],
    provinceList:[], // 省列表
    cityList:[],     // 市列表
    countyList:[],   // 区列表
    multiArray: [],
    multiIndex: [0, 0, 0],
    provinceId: "", //默认省份id
    cityId: "", //默认城市id
    positionFlag: 0, // 选择省市区标识
    buildList:[],
    page: 1,
    isRefresh: false,
    hasNoDatas: false,
    isIphoneX: app.globalData.isIphoneX,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserLocationInfo()
    this.getProvinces() // 获取省列表
  },
  //点击定位icon关闭搜索联想
  showPopup(){
    this.setData({
      searchList:[]
    })
  },
  //点击遮罩层关闭搜索联想
  tatchMaskBox(){
    this.setData({
      searchList:[]
    })
  },
  //input获取焦点时的处理函数
  inputFocusMethod(e){
    // console.log('inputFocusMethod', e)
    if(this.data.canSearch) { 
      this.inputChange(e)
    }
    setTimeout(()=>{
      this.setData({
        canSearch:true
      })
    },10)
  },
  //顶部搜索框失去焦点事件
  loseBlurMethods(e){
    setTimeout(()=>{
       this.setData({
       searchList:[]
    })
    },200)
  },
  //在楼盘下拉列表中选择楼盘事件
  selectBuildName(e){
    // console.log('selectBuildName', e)
    this.setData({
      canSearch:false
    })
    this.setData({
      buildName:e.currentTarget.dataset.name
    })
    this.setData({
      searchList:[]
    })
    this.loadNewData()
  },
  //顶部搜索input change事件
  inputChange(e){
    // console.log('inputChange', e)
    const val = e.detail.value

    this.setData({
      buildName: val
    })

    const str={
      buildingName: val.length > 0 ? val : this.data.buildName,
      location:this.data.subLocationInfo,
      page:1,
      rows: 200
    }
    utils.$http(app.globalData.api.getBuildNameList, str, 'GET', true, 'JSON').then(res=>{
      if(res.success === 1){
        this.setData({
          searchList:res.data.records
        })
      }
    })
  },
  //获取用户定位信息 
  getUserLocationInfo(){
    const latitude = wx.getStorageSync('latitude')
    const longitude = wx.getStorageSync('longitude')

    if(latitude === ""){
      this.setData({
        latitude:"",
        longitude:"",
        locationWidth:0
      })
      this.loadNewData()
    } else {
      this.setData({
        latitude,
        longitude,
        locationWidth:'120rpx'
      })
      this.handleGetCenterLocation()
    }
  },
  //获取当前位置的经纬度
  handleGetCenterLocation(){
    const that=this
    wx.getLocation({
      type: 'wgs84',
      success (res) {
        that.setData({
          latitude: res.latitude,
          longitude:res.longitude
        })
        that.handleUserPosition(res.latitude,res.longitude)
      }
    })
  },
  bindPickerChange(e) {
  //   console.log( e);
  //   console.log(this.data.countyList)
  //   console.log(this.data.cityList)
  //   const cityIndex=e.detail.value[1]
    const countyIndex = e.detail.value[2]
    const { latitude = '', longitude = '' } =  this.data.countyList && this.data.countyList[countyIndex]
    
    this.setData({
      positionFlag: 1,
      latitude,
      longitude,
    })
    this.handleUserPosition(latitude,longitude)
  },
    // 绑定选择器滑动事件
    bindMultiPickerColumnChange(e) {
      let that = this;
      // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
      let data = {
        multiArray: that.data.multiArray,
        multiIndex: that.data.multiIndex
      };
   
      data.multiIndex[e.detail.column] = e.detail.value;
      //data.multiIndex[0] : 第一列选择第几个
      //data.multiIndex[1] : 第二列选择第几个
      // console.log("multiIndex0:" + data.multiIndex[0])
      // console.log("multiIndex1:" + data.multiIndex[1])
   
      let provinceId = this.data.provinceList[data.multiIndex[0]].code; //获取选择到的省份id
      let cityId = this.data.cityList[data.multiIndex[1]].code; //获取选择到的市区id
   
      let obj = {
        provinceId: provinceId, //第一列父元素ID
        cityId: cityId, //第二列父元素ID
        that: that,
        column: e.detail.column,
        valueIndex: e.detail.value
      }
      this.changePicker(obj)
    },
    
  // 获取省列表
  getProvinces() {
    utils.$http(app.globalData.api.getProvinces, {}, 'GET', true, 'JSON').then(res => {
     if(res.success === 1) {
       if(Array.isArray(res.data)) {
        res.data.forEach(item => {item.text = item.name})
        this.setData({
          provinceList: res.data
        })
        this.getCities(res.data[0].code)
       }
     } 
    })
  },
  // 获取市列表
  getCities(parentCode) {
    utils.$http(app.globalData.api.getCities, { parentCode }, 'GET', true, 'JSON').then(res => {
     if(res.success === 1) {
       if(Array.isArray(res.data)) {
        res.data.forEach(item => {item.text = item.name})
        this.setData({
          cityList: res.data
        })

        this.getCounties(res.data[0].code)
       }
     } 
    })
  },
  // 获取区列表
  getCounties(parentCode) {
    utils.$http(app.globalData.api.getCounties, { parentCode }, 'GET', true, 'JSON').then(res => {
     if(res.success === 1) {
       if(Array.isArray(res.data)) {
        res.data.forEach(item => {item.text = item.name})
        this.setData({
          countyList: res.data,
          multiArray: [this.data.provinceList,this.data.cityList, res.data],
        })
       }
     } 
    })
  },
  
  //改变多列选择
 changePicker(obj) {
  let provinceId = obj.provinceId;
  let cityId = obj.cityId;
  let column = obj.column;
  let valueIndex = obj.valueIndex;
 
  let that = obj.that;
  let newArray1 = [], newArray2 = [];
  // console.log('provinceId:' + provinceId);

  let province_index = 0;
  //遍历省
  this.data.provinceList.map(function(value, index) {
    if (value.code == provinceId) {
      province_index = index;
 
      //请求市信息
      utils.$http(app.globalData.api.getCities, { parentCode: provinceId }, 'GET', true, 'JSON').then(res => {
        if(res.success === 1) {
          if(Array.isArray(res.data)) {
            that.setData({
             cityList: res.data
           })
            let dataArray = res.data
            newArray1 = dataArray;
            let city_index = 0;
            let countryId = newArray1[0].code;;
            newArray1.map(function(v2, i2) {
              if (v2.code == cityId) {
                city_index = i2;
                countryId = v2.code
              }
            })
            if (column == 2) {
              let selectId = that.data.countyList[valueIndex].code
              //不请求区县信息
              that.setData({
                multiIndex: [province_index, city_index, valueIndex],
                countryId: selectId
              })
            } else {
              //加载区县列表
              utils.$http(app.globalData.api.getCounties, { parentCode: countryId }, 'GET', true, 'JSON').then(resCounty => {
                if(resCounty.success === 1) {
                  if(Array.isArray(resCounty.data)) {
                    let dataArray2 = resCounty.data
                    newArray2 = dataArray2;
    
                    // 判断如果为空的情况下
                    if (newArray1.length == 0) {
                      newArray1.push({
                        id: '-1',
                        name: '-',
                      })
                    }
                    if (newArray2.length == 0) {
                      newArray2.push({
                        id: '-1',
                        name: '-',
                      })
                    }
                    let selectId = newArray2[0].code
                    that.data.cityList = newArray1;
                    that.data.countyList = newArray2;
    
                    that.setData({
                      multiArray: [that.data.provinceList, that.data.cityList, dataArray2],
                      multiIndex: [province_index, city_index, 0],
                      cityId: countryId,
                      countryId: selectId
                    })
                  }
                } 
               })
            }
          }
        } 
       })
    }
  }) 
},
  //获取当前经纬度定位
  handleUserPosition(lat,lon){
    utils.$http(app.globalData.api.getUserLocation, {latitude:lat,longitude:lon}, 'GET', true, 'JSON').then(res=>{
      if(res.success===1) {
        if(Object.keys(res.data).length > 0){
           this.setData({
            userLocation:res.data.district,
            subLocationInfo:res.data.province+'/'+res.data.city+'/'+res.data.district,
            locationWidth:'120rpx'
          })
          this.loadNewData()
        }
      }
    })
  },
  // 点击搜索icon搜索
  searchChange() {
    this.loadNewData()
  },
  // 回车搜索
  inputEnter() {
    this.loadNewData()
  },
  //获取所有楼盘列表
  handleGetBuildList(page = 1, type = 'new') {
    const params = {
      buildingName: this.data.buildName,
      location: this.data.subLocationInfo,
      page: page,
      rows:10
    }
    // console.log(params)
    utils.$http(app.globalData.api.getBuildNameList, params, 'GET', true, 'JSON').then(res=>{
      if(res.success === 1) {
        const { records = [] } = res.data
        if(type === 'more') {
          const list = this.data.buildList.concat(records)
          if(records.length === 0) {
            this.setData({
              hasNoDatas: true
            })
          } else {
            this.setData({
              buildList: list,
              hasNoDatas: false
            })
          }
        } else {
          this.setData({
            buildList: records,
            hasNoDatas: false
          })
        } 

        this.setData({
          searchList:[],
          isRefresh:false
        })
      }
    }).catch(() => {
      this.setData({
        isRefresh: false
      })
    })
  },
  loadNewData() {
    this.isRefresh = true
    this.data.page = 1 
    this.handleGetBuildList(this.data.page)
  },
  loadMoreData() {
    this.isRefresh = true
    this.data.page = this.data.page + 1 
    this.handleGetBuildList(this.data.page, 'more')
  },
  maskStartMove(e){
    this.setData({
      searchList:[],
      focusFlag:false
    })
  },
  //返回上一级页面
  goBackLasePage(){
    wx.navigateBack()
  },
  //点击进入楼盘详情
  goBuildDetail(e){
    const id=e.currentTarget.dataset.list
    wx.navigateTo({
      url: '/pages/housetype/housetype/index?id='+id
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})